package com.zheng.redpacket.server.utils.consumer;

import com.zheng.redpacket.server.dto.UserLoginDto;
import com.zheng.redpacket.server.serivce.SysLogService;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
public class UserLoginSubscriber implements ApplicationRunner, Ordered {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginSubscriber.class);
    private static final String topicKey = "redissonUserLoginTopicKey";

    @Autowired
    RedissonClient redisson;
    @Autowired
    SysLogService sysLogService;

    /**
     * 动态监听消息
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            RTopic rTopic = redisson.getTopic(topicKey);
            rTopic.addListener(UserLoginDto.class, new MessageListener<UserLoginDto>() {
                @Override
                public void onMessage(CharSequence charSequence, UserLoginDto dto) {
                    LOGGER.info("记录登录信息-消费者-监听到消息：{}", dto);
                    if (dto != null) {
                        sysLogService.recordLog(dto);
                    }
                }
            });
        } catch (Exception e) {
            LOGGER.error("记录登录信息-消费者-异常：", e.fillInStackTrace());
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
